package tom.client;

import java.util.List;

import tom.shared.InvItem;
import tom.shared.Invoice;
import tom.shared.LookupRecord;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.user.datepicker.client.DateBox.DefaultFormat;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.DoubleBox;
import com.google.gwt.user.client.ui.CheckBox;

public class LookupInvRefund extends Composite {

	private static final int RESULT_LIMITED = 500;

	private static DialogBox dlg;

	private static LookupInvRefund lookup;

	// private static String fname;

	private static TextBox output;

	private static TextBox rreason;

	private static Invoice curInv;

	private String status;

	private String contCode;

	public void setContact(String contCode) {
		this.contCode = contCode;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public void setSystemKind(String systemKind) {
		if (systemKind.equals("C"))
			docuKindC.setValue(true);
		else
			docuKindH.setValue(true);
	}

	public static void show(String title, TextBox output, TextBox rreason) {
		LookupInvRefund.output = output;
		LookupInvRefund.rreason = rreason;
		if (dlg == null) {
			lookup = new LookupInvRefund();
			dlg = GWT.create(DialogBox.class);
			dlg.setWidget(lookup);
			dlg.setModal(true);
		}
		lookup.setSystemKind("D");
		// lookup.setBalanceDue(balanceDue);
		dlg.setText(title);
		dlg.center();
		// if (!fname.equals(lastCode)) {
		// lookup.searchContact.setText(null);
		lookup.onBtnSearchClick(null);
		// }

		lookup.txtDocRef.setFocus(true);
	}

	private static LookupDialogUiBinder uiBinder = GWT
			.create(LookupDialogUiBinder.class);

	@UiField
	AbsolutePanel aPanel;
	@UiField
	Button btnSearch;
	@UiField
	TextBox txtDocRef;
	@UiField
	Button btnOK;
	@UiField
	Button btnCancel;
	@UiField
	Button btnClear;
	@UiField
	Label recordCount;
	@UiField
	RadioButton docuKindC;
	@UiField
	RadioButton docuKindH;
	@UiField
	Label label01;
	@UiField
	Button btnResLookup;
	@UiField
	TextBox txtResCode;
	@UiField
	TextBox txtReason;
	@UiField
	RadioButton docuKindS;
	@UiField
	RadioButton docuKindI;
	private final ListDataProvider<Invoice> itemData = new ListDataProvider<Invoice>();
	private final CellTable<Invoice> itemTable = new CellTable<Invoice>();
	private final SingleSelectionModel<Invoice> itemSelection = new SingleSelectionModel<Invoice>();

	private void disableSearch() {
		label01.setVisible(false);
		// label02.setVisible(false);
		// label03.setVisible(false);
		docuKindC.setVisible(false);
		docuKindH.setVisible(false);
		// balanceDue.setVisible(false);
		txtDocRef.setVisible(false);
		// totalAmt.setVisible(false);
		// /searchDate.setVisible(false);
	}

	List<LookupRecord> list;

	interface LookupDialogUiBinder extends UiBinder<Widget, LookupInvRefund> {
	}

	public LookupInvRefund() {
		initWidget(uiBinder.createAndBindUi(this));
		// disableSearch();

		// searchDate.setFormat(new DefaultFormat(Library.DATE_FORMAT));
		ScrollPanel listPanel = new ScrollPanel();
		listPanel.setSize("750px", "320px");
		this.aPanel.add(listPanel, 20, 75);
		itemTable.setStyleName("table");
		listPanel.setWidget(itemTable);
		itemTable.setSelectionModel(itemSelection);

		itemSelection
				.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
					@Override
					public void onSelectionChange(SelectionChangeEvent event) {
						curInv = itemSelection.getSelectedObject();
					}
				});

		TextColumn<Invoice> colDocRef = new TextColumn<Invoice>() {
			@Override
			public String getValue(Invoice object) {
				return object.docRef;
			}
		};
		// colProCode.setCellStyleNames("table");
		itemTable.addColumn(colDocRef, "เลขที่บิล");
		itemTable.setColumnWidth(colDocRef, "120px");

		TextColumn<Invoice> colSaleDate = new TextColumn<Invoice>() {
			@Override
			public String getValue(Invoice object) {
				return Library.DATE_FORMAT.format(object.invDate);
			}
		};
		// colProCode.setCellStyleNames("table");
		itemTable.addColumn(colSaleDate, "วันที่บิล");
		itemTable.setColumnWidth(colSaleDate, "95px");

		TextColumn<Invoice> colTotalAmt = new TextColumn<Invoice>() {
			@Override
			public String getValue(Invoice object) {
				return Library.moneyFormat(object.totalAmt);
			}
		};
		colTotalAmt.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
		colTotalAmt.setCellStyleNames("table");
		itemTable.addColumn(colTotalAmt, "มูลค่า");
		itemTable.setColumnWidth(colTotalAmt, "95px");

		TextColumn<Invoice> colBalance = new TextColumn<Invoice>() {
			@Override
			public String getValue(Invoice object) {
				return Library.moneyFormat(object.totalAmt - object.totalPaid);
			}
		};
		colBalance.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
		colBalance.setCellStyleNames("table");
		itemTable.addColumn(colBalance, "ค้างชำระ");
		itemTable.setColumnWidth(colBalance, "95px");

		TextColumn<Invoice> colAddr = new TextColumn<Invoice>() {
			@Override
			public String getValue(Invoice object) {
				return object.contactAddr;
			}
		};
		itemTable.addColumn(colAddr, "ที่อยู่");
		itemTable.setColumnWidth(colAddr, "800px");

		itemData.addDataDisplay(itemTable);
		itemTable.setPageSize(40);
		itemTable.setTableLayoutFixed(true);
		itemTable.setAccessKey('x');
		itemTable.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
		itemTable.setHeight("100%");
		itemTable.setWidth("100%", true);

	}

	private AsyncCallback<List<Invoice>> invCallback = new AsyncCallback<List<Invoice>>() {

		@Override
		public void onFailure(Throwable caught) {

		}

		@Override
		public void onSuccess(List<Invoice> result) {
			itemData.setList(result);
			itemData.refresh();
			recordCount.setText(String.valueOf(result.size())
					+ " รายการ"
					+ (result.size() > RESULT_LIMITED ? " แสดงเพียง "
							+ RESULT_LIMITED + " รายการ" : ""));
			btnSearch.setEnabled(true);
			txtDocRef.setEnabled(true);
			// txtDocRef.setFocus(true);
			itemSelection.setSelected(result.get(0), true);
			itemTable.setFocus(true);
		}
	};

	@UiHandler("btnSearch")
	void onBtnSearchClick(ClickEvent event) {
		recordCount.setText("กำลังดึงข้อมูล...");
		btnSearch.setEnabled(false);
		txtDocRef.setEnabled(false);
		// Library.getService().lookupList(fname, textSearch.getText(),
		// recordCallback);
		String docuKind = null;
		if (docuKindC.getValue())
			docuKind = "C";
		else if (docuKindH.getValue())
			docuKind = "H";
		else if (docuKindI.getValue())
			docuKind = "I";
		else if (docuKindS.getValue())
			docuKind = "S";

		Library.getSaleService().searchInvoice(txtDocRef.getValue(), null,
				docuKind, "D", "", false, null, contCode, status, invCallback);
	}

	@UiHandler("btnCancel")
	void onBtnCancelClick(ClickEvent event) {
		output.setFocus(true);
		dlg.hide();
	}

	@UiHandler("btnOK")
	void onBtnOKClick(ClickEvent event) {
		if (txtReason.getValue() == null || txtReason.getValue().equals("")) {
			Window.alert("เลือกเหตุผลการลดหนี้");
		} else {
			if (curInv != null) {
				output.setText(curInv.invNo.toString());
				rreason.setText(txtResCode.getValue());
			}
			onBtnCancelClick(null);
			output.fireEvent(Library.KEY_ENTER_EVENT);
		}
	}

	@UiHandler("btnClear")
	void onBtnClearClick(ClickEvent event) {
		txtDocRef.setText(null);
		// onBtnCancelClick(null);
		txtDocRef.fireEvent(Library.KEY_ENTER_EVENT);
		txtDocRef.setFocus(true);
	}

	@UiHandler("btnResLookup")
	void onBtnResLookupClick(ClickEvent event) {
		LookupDialog.show("เหตุผลการลดหนี้", "resCode", txtResCode, txtReason);
	}

	@UiHandler("docuKindI")
	void onDocuKindIClick(ClickEvent event) {
		onBtnSearchClick(event);
	}

	@UiHandler("docuKindH")
	void onDocuKindHClick(ClickEvent event) {
		onBtnSearchClick(event);
	}

	@UiHandler("docuKindC")
	void onDocuKindCClick(ClickEvent event) {
		onBtnSearchClick(event);
	}

	@UiHandler("docuKindS")
	void onDocuKindSClick(ClickEvent event) {
		onBtnSearchClick(event);
	}

}
